package com.hk.service.impl;

import com.hk.commons.Chart.BrokenLineChartMsg;
import com.hk.commons.Chart.ComparisonChartMsg;
import com.hk.commons.EmailRes;
import com.hk.commons.HttpUtils;
import com.hk.commons.entity.Organization;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.commons.vo.Returnsms;
import com.hk.service.IMsg;
import com.hk.service.IOrganization_New;
import com.hk.service.sys.IChart;
import com.hk.service.sys.ISysUserRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ChartImpl implements IChart {
    private Logger logger = LoggerFactory.getLogger(ChartImpl.class);

    @Autowired
    private IOrganization_New orgNewService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public BrokenLineChartMsg getOrderBrokenLineGraph(Integer orgId) {

        List<Organization> orgList = orgNewService.getSubDepList(orgId);
        if(orgList == null || orgList.size() == 0){
            return null;
        }



        String sql = "select distinct left(from_unixtime(orderCreatedOn/1000), 7) as time from t_order_info  order by time ";

        List<String> timeList = this.jdbcTemplate.queryForList(sql, String.class);

        List<String> orgNameList = orgList.parallelStream()
                                    .map(org->org.getName())
                                    .collect(Collectors.toList());;


        BrokenLineChartMsg brokenLineChartMsg = new BrokenLineChartMsg();

        logger.info("name list size ={}", timeList.size());

        List<Map<String, Object>> nodeData = orgList.parallelStream()
                .map(org -> getNodeData(org, timeList))
                .collect(Collectors.toList());

        brokenLineChartMsg.setNameList(timeList);
        brokenLineChartMsg.setData(nodeData);
        brokenLineChartMsg.setOrtNameList(orgNameList);

        return brokenLineChartMsg;
    }

    @Override
    public ComparisonChartMsg  getOrderComparisonGraph(Integer orgId) {


        List<Organization> orgList = orgNewService.getSubDepList(orgId);
        if(orgList == null || orgList.size() == 0){
            return null;
        }

        ComparisonChartMsg comparisonChartMsg = new ComparisonChartMsg();

        List<String> nameList = new ArrayList<>();
        List<String> saleAmount = new ArrayList<>();

        for(Organization org:orgList){
            nameList.add(org.getName());


            String sql = "SELECT sum(successAmount) FROM t_order_info where orgId in (select id from t_organization where code  like '" + org.getCode() + "-%' )";


            BigDecimal totalAmount = jdbcTemplate.queryForObject(sql,
                    BigDecimal.class);
            if( totalAmount == null) {
                totalAmount = new BigDecimal(0);
            }

            saleAmount.add(totalAmount.toString());
        }

        comparisonChartMsg.setNameList(nameList);
        comparisonChartMsg.setValueList(saleAmount);

        return comparisonChartMsg;
    }

    @Override
    public List<Map<String, Object>> getOrderIn(Integer orgId) {

        List<Organization> orgList = orgNewService.getSubDepList(orgId);
        if(orgList == null || orgList.size() == 0){
            return null;
        }



        List<Map<String, Object>> resultList  = new ArrayList<Map<String, Object>>();

        for(Organization org:orgList){
            String sql = "SELECT sum(successAmount) FROM t_order_info where orgId in (select id from t_organization where code  like '" + org.getCode() + "-%' )";
            BigDecimal totalAmount = jdbcTemplate.queryForObject(sql, BigDecimal.class);
            if( totalAmount == null) {
                totalAmount = new BigDecimal(0);
            }

            Map<String, Object> node = new HashMap<>();
            node.put("name", org.getName());
            node.put("value", totalAmount);

            resultList.add(node);

        }

        return resultList;
    }

    @Override
    public List<Object> getUserComparisonGraph(Integer orgId) {
        return null;
    }

    @Override
    public List<Object> getUserIn(Integer orgId) {
        return null;
    }

    @Override
    public List<Object> getUserBrokenLineGraph(Integer orgId) {
        return null;
    }

    public Map<String, Object> getNodeData(Organization org, List<String> timeList){
        Map<String, Object> node = new HashMap<String, Object>();

        node.put("name", org.getName());
        node.put("type",  "line");
        node.put("stack",  "销售额");

        List<String > amtList = timeList.parallelStream()
                .map(time->getAmt(org, time).toString())
                .collect(Collectors.toList());

//        for(String time:timeList){
//
//            String amountSql = "select  sum(successAmount) as amount from t_order_info  where orgId in (select id from t_organization where code  like '" + org.getCode() + "-%' ) and left(from_unixtime(orderCreatedOn/1000), 7) = '" + time+ "'";
//
//            BigDecimal totalAmount = jdbcTemplate.queryForObject(amountSql, BigDecimal.class);
//
//            if( totalAmount == null) {
//                totalAmount = new BigDecimal(0);
//            }
//            amtList.add(totalAmount.toString());
//        }

        node.put("data",  amtList);

        return node;
    }

    private BigDecimal getAmt(Organization org, String time){
        String amountSql = "select  sum(successAmount) as amount from t_order_info  where orgId in (select id from t_organization where code  like '" + org.getCode() + "-%' ) and left(from_unixtime(orderCreatedOn/1000), 7) = '" + time+ "'";

        BigDecimal totalAmount = jdbcTemplate.queryForObject(amountSql, BigDecimal.class);

        if( totalAmount == null) {
            totalAmount = new BigDecimal(0);
        }

        return  totalAmount;

    }
}
